<?php

class ResizeImage {

    var $max_width;
    var $max_height;
    var $path;
    var $img;
    var $new_width;
    var $new_height;
    var $mime;
    var $image;
    var $width;
    var $height;

    function max_width($width) {
        if ($width == "" || is_null($width)) {
            $width = 0;
        }
        $this->max_width = $width;
    }

    function max_height($height) {
        if ($height == "" || is_null($height))
            $height = 0;
        $this->max_height = $height;
    }

    function image_path($path) {
        $this->path = $path;
    }

    function get_mime() {
        $img_data = getimagesize($this->path);
        $this->mime = $img_data['mime'];
    }

    function create_image() {
        switch ($this->mime) {
            case 'image/jpeg':
                $this->image = imagecreatefromjpeg($this->path);
                break;

            case 'image/gif':
                $this->image = imagecreatefromgif($this->path);
                break;

            case 'image/png':
                $this->image = imagecreatefrompng($this->path);
                break;
        }
    }

    function image_resize() {
        set_time_limit(120);
        $this->get_mime();
        $this->create_image();
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
        $this->set_dimension();
        $image_resized = imagecreatetruecolor($this->new_width, $this->new_height);
        imagecopyresampled($image_resized, $this->image, 0, 0, 0, 0, $this->new_width, $this->new_height, $this->width, $this->height);
        imagejpeg($image_resized, $this->path);
    }

    //######### FUNCTION FOR RESETTING DEMENSIONS OF IMAGE ###########
    function set_dimension() {
        //si el ancho o alto es igual a cero entonces se calcula el valor de manera proporcional
        if ($this->max_width <= 0 || $this->max_height <= 0) {
            if ($this->max_width <= 0) {
                $this->max_width = $this->width / ($this->height / $this->max_height);
            } elseif ($this->max_height <= 0) {
                $this->max_height = $this->height / ($this->width / $this->max_width);
            }
        }

        //si el ancho de la imagen original es menor que el ancho maximo entonces deja el ancho original
        if ($this->width <= $this->max_width) {
            $this->new_height = $this->width;
        }

        //si el ancho de la imagen original es menor o igual que el ancho maximo entonces deja el ancho original
        if ($this->width <= $this->max_width) {
            $this->max_width = $this->width;
        }

        //si el alto de la imagen original es menor o igual que el alto maximo entonces deja el alto original
        if ($this->height <= $this->max_height) {
            $this->max_height = $this->height;
        }

        //asigna las nuevas dimensiones
        $this->new_width = $this->max_width;
        $this->new_height = $this->max_height;
    }

}

?>
